import {
  Component, OnInit, OnDestroy, ViewEncapsulation, ViewChild
} from '@angular/core';
import {ActivatedRoute, Params, Router} from "@angular/router";
import {ToolsService} from "@shared/service/tools/tools.service";
import {HaggleService} from "./haggle.service";
import {Subject} from "rxjs/Rx";
import {HaggleActivityRespVO, HaggleInitiatorRespVO} from "@interface/index";
import {EventsService} from "@core/events/events.service";

import {AuthService} from "@shared/service/auth/auth.service";
import {GoodsService} from "@goods/goods.service";
import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";

@Component({
  selector: 'seed-haggle',
  templateUrl: './haggle.component.html',
  styleUrls: ['./haggle.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class HaggleComponent implements OnInit, OnDestroy {
  @ViewChild('modal1') modal1;
  @ViewChild('modal2') modal2;
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  @ViewChild('redirectBtn') redirectBtn: HTMLLinkElement;

  public markType: number; // 按钮显示状态
  public haggleUserList: Array<HaggleInitiatorRespVO> = []; // 砍价高手列表
  public haggleInfo: HaggleActivityRespVO = new HaggleActivityRespVO();
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public userId: string;
  public haggleId: number; // 活动ID
  public initiatorId: string; // 活动发起人
  public haggleUserId: string; // 砍价人
  public activityStatus: number; // 当前发起人发起的活动状态（0：已经结束，1：进行中)
  private $activityStatus: Subject<boolean> = new Subject<boolean>();
  public currentUserHaggled = false; // 当前用户是否 已 砍价
  public currentInitiated = false; // 当前用户是否 发起过活动

  public dataStore = {
    page: 1,
    timer: null, // 定时器
    onceHaggleAmount: 0, // 一次砍价的金额
    totalHaggleAmount: 0, // 砍价总金额
  };

  public param = {
    page: 1,
    rows: 10,
  };

  public times = {
    nowTime: '',
    day: '0',
    hour: '00',
    minute: '00',
    second: '00',
  };

  constructor(
    public router: Router,
    public route: ActivatedRoute,
    public tools: ToolsService,
    public user: AuthService,
    public events: EventsService,
    public goodsService: GoodsService,
    public haggleService: HaggleService
  ) {
    this.route.params.switchMap((params: Params) => {
      this.userId = this.user.getUserId();
      this.haggleId = params['haggleId'];
      this.markType = 1;
      return this.route.queryParams;
    }).subscribe((queryParams: Params) => {
      if (this.haggleId) {
        // 当链接中 无发起人 ，把当前用户作为发起人，跳转至下方第二种链接
        if (this.haggleId && !queryParams['initiatorId'] && !queryParams['haggleUserId']) {
          if (!this.user.hasLoggedIn() && !this.user.getUserId()) { // 初始化时判断是否登陆，未登录
            this.getHaggleDetail({haggleId: this.haggleId});
          } else {

            this.goToHaggleInitiate();  // 跳转带有initiatorId参数的url

            return;
          }
        } else if (this.haggleId && queryParams['initiatorId']) { // 当链接中 有发起人 参数，以携带参数为准
          this.initiatorId = queryParams['initiatorId'];
          const query = {
            haggleId: this.haggleId,
            initiatorId: this.initiatorId
          };

          if (!this.user.hasLoggedIn() && !this.user.getUserId()) { // 初始化时判断是否登陆，未登录
            this.getHaggleDetail(query);
          }else {
            this.haggleUserId = this.userId; // 砍价人只能为 当前登录用户；
            const param = Object.assign({}, query, {
              haggleUserId: this.haggleUserId
            });
            this.getHaggleDetail(param);
          }
/*          setTimeout( () => {
            if (this.dataStore.totalHaggleAmount) {
              this.handleReHaggleUsers();
            }
          }, 300);*/

          // 如果发起人没有发起过砍价活动, 有值发起过活动，activityStatus: 1 结束，0 进行中
          this.$activityStatus.subscribe(res => {
            if (res && !this.activityStatus && this.initiatorId === this.userId && !this.currentInitiated) {

              this.postHaggleInitiate(); // 未发起过活动，则执行发起

            }
          });

        }
      }
    });
  }


  /**
   * @description 获取砍价信息
   * @anthor @zhupw1360
   * @date 20180302
   * modify 2018-04-03
   * @param haggleId
   */
  getHaggleDetail(query) {
    this.haggleService.getHaggleDetail(query)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '105017' || !res.data) {
          this.tools.presentOnceConfirm('抱歉！该活动不存在', () => {
            this.goToHome();
          }, '确定');
        }
        if (res.result === '0' && res.data) {
          this.haggleInfo = res.data;
          this.activityStatus = res.data.myInitiateActivityStatus;
          this.dataStore.totalHaggleAmount = res.data.haggleAmount ? res.data.haggleAmount : 0.00 ;
          if ( this.dataStore.totalHaggleAmount > 0 ) {
            this.handleReHaggleUsers();
          }
          if (this.user.hasLoggedIn() && this.user.getUserId()) {
            this.currentUserHaggled = res.data.currentUserHaggled;
            this.currentInitiated = res.data.currentInitiated;
          }
          this.$activityStatus.next( true);
          this.dataStore.timer = setInterval(this.handleCountdown.bind(this), 1000);
          this.handleButtonShow();
        }

      });
  }

  // 发起砍价活动（有发起人 且没有发起过活动时）
  postHaggleInitiate() {
    this.haggleService.postHaggleInitiate({haggleId: this.haggleId})
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      // if (this.haggleInfo.haggleStatus === 0) {
      //   return;
      // }
      // if (this.haggleInfo.haggleStatus === 2) {
      //   return;
      // }
      if (this.haggleInfo.haggleStatus === 1) {
        if (res.result === '0' && res.data) {
          this.handleButtonShow();
        }
      }
    });
  }

  // 点击砍一刀减金额
  postHaggleSum() {
    const query = {
      haggleId: this.haggleId,
      initiatorId: this.initiatorId
    };
    this.haggleService.postHaggleSum(query)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (this.haggleInfo.haggleStatus === 0) {
        this.tools.showToast('活动尚未开始，请耐心等待');
        return;
      }
      if (this.haggleInfo.haggleStatus === 2) {
        this.tools.showToast('活动已结束，请关注其他活动');
        return;
      }
      if (this.haggleInfo.haggleStatus === 1) {
        if (res.result === '105014'  ) {
          this.tools.showToast('助力已结束，不能再助力了，亲');
          return;
        }
        if (res.result === '105008' || res.result === '105012') {
          this.tools.showToast('助力成功，您已无法再砍');
          return;
        }
        if (res.result === '105017') {
          this.tools.showToast('该砍价活动不存在');
          return;
        }
        if (res.result === '105018') {
          this.tools.showToast('该砍价活动发起人不存在');
          return;
        }
        if (res.result === '0' && res.data) {
          this.dataStore.onceHaggleAmount = res.data;
          this.currentUserHaggled = true;
          this.modal1.show();
          this.handleButtonShow();
          this.dataStore.totalHaggleAmount += res.data;
          this.handleReHaggleUsers();
        }
      }
    });
  }


  // 刷新页面，重新刷新 助力人列表
  handleReHaggleUsers() {
    this.dataStore.page = 1;
    this.haggleUserList = [];
    this.getHaggleUsers();
  }

  // 处理砍价活动是否登录
  handleHaggleInitiate() {
    if (!this.user.hasLoggedIn() && !this.user.getUserId()) {
      this.tools.presentConfirm('此操作需要登录,是否前往登录', 1, this.goToLogin.bind(this));
    } else {
      this.postHaggleSum();
    }
  }

  // 跳转登录页面
  goToLogin() {
    this.user.redirectUrl = !!this.initiatorId ? `/haggle/${this.haggleId}?initiatorId=${this.initiatorId}` : `/haggle/${this.haggleId}` ;
    this.router.navigate(['/auth/login']);
  }

  // 跳转首页
  goToHome() {
    this.router.navigate(['/']);
  }

  // 获取帮忙砍价用户列表
  getHaggleUsers() {
    const query = {
      page: this.dataStore.page,
      rows: 10,
      haggleId: this.haggleId,
      initiatorId: this.initiatorId
    };
    this.haggleService.getHaggleUsers(query)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '0' && res.data.list && res.data.list.length > 0) {
          if ( this.dataStore.totalHaggleAmount > 0 ) {
            this.infiniteScroll.enable(true);
          }
          this.infiniteScroll && this.infiniteScroll.complete();
          this.dataStore.page++;
          this.haggleUserList = [...this.haggleUserList, ...res.data.list];
          if (!res.data.hasNextPage) {
            this.infiniteScroll.enable(false);
          }
        }
      });
  }

  // 处理活动倒计时
  handleCountdown() {
    const nowTime: number = new Date().getTime();
    let t = this.haggleInfo.endTime - nowTime;
    if ( this.haggleInfo.haggleStatus === 2 || this.haggleInfo.status === 1 ) { // 如果活动已经结束 或 商品已下架，
      this.markType = 5;
      clearInterval(this.dataStore.timer);
    }
    if ((this.haggleInfo.haggleStatus === 0 || this.haggleInfo.haggleStatus === 3) && this.haggleInfo.status === 0) {
      // 如果活动还没开始且商品未下架，活动将在XX时间后开始
      this.markType = 6;
      clearInterval(this.dataStore.timer);
    }
    if ((this.haggleInfo.haggleStatus === 1 && this.haggleInfo.haggleStatus !== 3 ) && this.haggleInfo.status === 0) {
      // 如果活动已经开始且商品未下架， 活动将在XX时间后结束
      t = Math.abs(t) ;
    }

    let hour, minute, second;
    this.times.day = Math.floor(t / 1000 / 60 / 60 / 24).toString();
    hour = Math.floor(t / 1000 / 60 / 60 % 24).toString();
    minute = Math.floor(t / 1000 / 60 % 60).toString();
    second = Math.floor(t / 1000 % 60).toString();
    this.times.hour = this.handleTime(hour);
    this.times.minute = this.handleTime(minute);
    this.times.second = this.handleTime(second);
  }
  // 处理个位数时间
  handleTime(time) {
    if (time > 0 && time < 10) {
      return `0${time}`;
    } else {
      return time;
    }
  }


  // 关闭模态框
  closeModal() {
    this.modal1.hide();
    this.modal1.goBack();
  }

  // 分享链接指引-弹框
  haggleShared() {
    this.modal2.show();
  }

  /**
   * @description 跳转商品详情
   * @author ouyqx-691
   * @param goodsCode
   */
  goToGoodsDetail(goodsCode: string) {
    if (goodsCode) {
      this.router.navigate(['/goods/detail', goodsCode]);
    }
  }

  /**
   * @description 发送订单
   * @author @zhupw1360
   * @date 2018-03-09
   * @param skuListpublic
   */
  sendOrderToConfirm() { // 发送订单前 判断是否已经下过单 有记录则弹框提示
    if ( this.activityStatus === 1) {
      this.tools.showToast('该活动已提交过订单，请在订单中查看');
      return;
    } else {
      const params = {
        'detailList[0].skuCode': this.haggleInfo.goodsSku,
        'detailList[0].quantity': 1,
      };
      this.goodsService.sendOrderToConfirm(params).subscribe(res => {
        const paramsTwo = {
          goodsCateCode: this.haggleInfo.goodsCode,
          haggleId: this.haggleId,
          initiatorId: this.initiatorId,
          skuCode: this.haggleInfo.goodsSku,
          quantity: 1
        };

        this.goodsService.showGoodsResultMsg(res.result, res.msg, paramsTwo);
      });
    }

  }

  // 处理当前页面 button 的不同状态
  handleButtonShow() {
    if (this.haggleInfo.status === 1 || this.activityStatus === 1) {
      this.markType = 5;
      clearInterval(this.dataStore.timer);
      return;
    }
    if (!this.initiatorId || this.initiatorId === this.userId) { // 自己发起的砍价活动
      this.markType = 1; // 未砍价
      if (this.initiatorId === this.userId && this.currentUserHaggled) { // 活动为我发起时，并且我砍过价且有砍价数据时
        this.markType = 2; // 自己已砍价
      }
    } else {
      this.markType = 3; // 他人发起的砍价活动 - 未砍价
      if (this.initiatorId !== this.userId && this.currentUserHaggled) { // 活动为他人发起时，并且我砍过价且有砍价数据时
        this.markType = 4; // 当前用户替别人已砍价
      }
    }
  }

  /** 1.一开始进入页面刷新
   *  2.点击 我也要，需变更链接后续才可以分享 markType=1
   *  (使用IOS系统的微信打开链接需要更新链接，刷新进入页面； 否则跳转路由）
   * */
  goToHaggleInitiate() {

    if (this.tools.ua().isWeixin && this.tools.ua().isIos) {
      window.location.href = window.location.protocol + `haggle/${this.haggleId}?initiatorId=${this.userId}`;
    } else {
      this.router.navigate(['/haggle', this.haggleId], {
        queryParams: { initiatorId: this.userId },
        replaceUrl: true
      });
    }
    this.markType = 1;
  }


  ngOnInit() {
    this.infiniteScroll && this.infiniteScroll.enable(false);
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}
